RenderBatch = RenderBatch or Class("RenderBatch")

---@diagnostic disable-next-line: duplicate-set-field
function RenderBatch:ctor(renderInfo)
    self.renderType = renderInfo.renderType
    if self.renderType == RenderType.Mesh then
        self.vertexMap = {}
        self.vertices = {}
        self.material = renderInfo.material
        self:_batch(renderInfo)
    elseif self.renderType == RenderType.Text then
        self.text = renderInfo.text
        self.color = renderInfo.color
        self.args = renderInfo.args
    elseif self.renderType == RenderType.Scissor then
        self.args = renderInfo.args
    end
end
VertexMax = 65535
function RenderBatch:tryBatch(renderInfo)
    if self.renderType == RenderType.Text then
        return false
    end
    if self.renderType == RenderType.Scissor then
        return false
    end
    if renderInfo.material ~= self.material then
        return false
    end
    if #self.vertices + #renderInfo.vertices > VertexMax then
        return false
    end
    self:_batch(renderInfo)
    return true
end

function RenderBatch:_batch(renderInfo)
    local start = #self.vertices
    for i, v in ipairs(renderInfo.vertexMap) do
        table.insert(self.vertexMap, v + start)
    end
    for i, v in ipairs(renderInfo.vertices) do
        table.insert(self.vertices, v)
    end
end

function RenderBatch:draw()
    if self.renderType == RenderType.Text then
        self:drawText()
    elseif self.renderType == RenderType.Mesh then
        self:drawMesh()
    end
end

function RenderBatch:drawText()
    local wx, wy, wr, wsx, wsy, ox, oy, kx, ky = unpack(self.args)
    love.graphics.setColor(self.color:unpack())
    love.graphics.draw(self.text, wx, wy, wr, wsx, wsy, ox, oy, kx, ky)
    love.graphics.setColor(1, 1, 1, 1)
end

function RenderBatch:drawMesh()
    local mat = self.material
    local curMesh = love.graphics.newMesh(mat.vertexFormat, self.vertices, "triangles")
    curMesh:setVertexMap(self.vertexMap)
    if mat.texture then
        curMesh:setTexture(mat.texture)
    end
    love.graphics.setShader(mat.shader)
    love.graphics.draw(curMesh)
end